package api

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/model/example"
	picModel "counter-help/admin/server/plugin/picturelibrary/model"
	"counter-help/admin/server/plugin/picturelibrary/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
)

type PictureLibraryApi struct{}

var picService = service.ServiceGroupApp

// @Tags PictureLibrary
// @Summary 请手动填写接口功能
// @Produce  application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
// @Router /图片库/routerName [post]
func (p *PictureLibraryApi) ApiName(c *gin.Context) {

	if err := picService.PlugService(); err != nil {
		global.GVA_LOG.Error("失败!", zap.Error(err))
		response.FailWithMessage("失败", c)
	} else {

		response.OkWithData("成功", c)
	}
}

// GetFileList
// @Tags      sysAttachment
// @Summary   分页文件列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.PageInfo                                        true  "页码, 每页大小"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页文件列表,返回包括列表,总数,页码,每页数量"
// @Router    /attachment/getFileList [post]
func (p *PictureLibraryApi) GetFileList(c *gin.Context) {
	var pageInfo picModel.PageInfo
	_ = c.ShouldBindJSON(&pageInfo)
	list, total, err := picService.GetFileRecordInfoList(pageInfo, c)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.Limit,
	}, "获取成功", c)
}

// GetCategoryList
// @Tags      sysAttachment
// @Summary   分类列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.PageInfo                                        true  "页码, 每页大小"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页文件列表,返回包括列表,总数,页码,每页数量"
// @Router    /attachment/getFileList [post]
func (p *PictureLibraryApi) GetCategoryList(c *gin.Context) {
	db := global.GVA_DB.Model(&picModel.SysAttachmentCategory{})
	var fileLists []picModel.SysAttachmentCategory
	err := db.Find(&fileLists).Error
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	data := picService.BuildTree(fileLists, 0)
	response.OkWithDetailed(response.PageResult{
		List: data,
	}, "获取成功", c)
}

// AddCategory
// @Tags      sysAttachment
// @Summary   添加分类
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.PageInfo                                        true  "页码, 每页大小"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页文件列表,返回包括列表,总数,页码,每页数量"
// @Router    /attachment/getFileList [post]
func (p *PictureLibraryApi) AddCategory(c *gin.Context) {
	var input struct {
		Name string `json:"name" binding:"required"`
		Pid  uint   `json:"pid" binding:"required"`
		Id   uint   `json:"id"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		global.GVA_LOG.Error("参数错误!", zap.Error(err))
		response.FailWithMessage("参数错误", c)
		return
	}

	// 检查是否已存在相同名称的分类
	var existingCategory picModel.SysAttachmentCategory
	result := global.GVA_DB.Where("name = ? ", input.Name).First(&existingCategory)
	if result.Error == nil && existingCategory.Id != input.Id {
		response.FailWithMessage("分类名称已存在", c)
		return
	}

	// 创建新的分类
	newCategory := picModel.SysAttachmentCategory{Name: input.Name, Pid: input.Pid}
	var err error
	var title string
	if input.Id > 0 {
		err = global.GVA_DB.Where("id = ?", input.Id).Updates(newCategory).Error
		title = "更新失败"
	} else {
		err = global.GVA_DB.Create(&newCategory).Error
		title = "创建失败"
	}
	if err != nil {
		response.FailWithMessage(title, c)
		return
	}

	response.OkWithDetailed(response.PageResult{}, "创建成功", c)
}

// UploadHandler
// @Tags      sysAttachment
// @Summary   多文件上传
// @Security  ApiKeyAuth
// @accept    multipart/form-data
// @Produce   application/json
// @Param     file  formData  [file]                                                           true  "上传文件示例"
// @Success   200   {object}  response.Response{data=exampleRes.ExaFileResponse,msg=string}  "上传文件示例,返回包括文件详情"
// @Router    /fileUploadAndDownload/upload [post]
func (p *PictureLibraryApi) UploadHandler(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["files"]
	categoryIDStr := c.PostForm("cat_id")
	categoryID, _ := strconv.ParseUint(categoryIDStr, 10, 32)
	noSave := c.DefaultQuery("noSave", "0")
	for _, file := range files {
		fileData, err := fileUploadAndDownloadService.UploadFile(file, noSave)
		if err != nil {
			global.GVA_LOG.Error("上传失败!", zap.Error(err))
			response.FailWithMessage("上传失败", c)
			return
		}
		var attachment picModel.SysAttachment
		if err := global.GVA_DB.Where("`key` = ? ", fileData.Key).First(&attachment).Error; err != nil {
			response.FailWithMessage("上传失败", c)
			return
		}
		// 根据key更新数据
		attachment.CatId = uint(categoryID)
		if err := global.GVA_DB.Save(&attachment).Error; err != nil {
			response.FailWithMessage("上传文件失败", c)
			return
		}
	}
	response.OkWithDetailed(response.PageResult{}, "上传成功", c)
}

// DeleteFile
// @Tags      sysAttachment
// @Summary   删除文件
// @Security  ApiKeyAuth
// @Produce   application/json
// @Param     data  body      example.ExaFileUploadAndDownload  true  "传入文件里面id即可"
// @Success   200   {object}  response.Response{msg=string}     "删除文件"
// @Router    /fileUploadAndDownload/deleteFile [post]
func (p *PictureLibraryApi) DeleteFile(c *gin.Context) {
	var files []example.ExaFileUploadAndDownload
	err := c.ShouldBindJSON(&files)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	for _, file := range files {
		if err := fileUploadAndDownloadService.DeleteFile(file); err != nil {
			global.GVA_LOG.Error("删除失败!", zap.Error(err))
			response.FailWithMessage("删除失败", c)
			return
		}
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteCategory
// @Tags      sysAttachment
// @Summary   删除分类
// @Security  ApiKeyAuth
// @Produce   application/json
// @Param     data  body      example.ExaFileUploadAndDownload  true  "传入文件里面id即可"
// @Success   200   {object}  response.Response{msg=string}     "删除文件"
// @Router    /fileUploadAndDownload/deleteFile [post]
func (p *PictureLibraryApi) DeleteCategory(c *gin.Context) {
	var input struct {
		CatId uint `json:"cat_id"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}
	if input.CatId == 0 {
		response.FailWithMessage("参数错误-1", c)
		return
	}
	var childCount int64
	global.GVA_DB.Model(&picModel.SysAttachmentCategory{}).Where("pid = ?", input.CatId).Count(&childCount)

	if childCount > 0 {
		response.FailWithMessage("请先删除子级", c)
		return
	}
	result := global.GVA_DB.Delete(&picModel.SysAttachmentCategory{}, input.CatId)
	if result.Error != nil {
		response.FailWithMessage("删除失败", c)
		return
	}

	response.OkWithMessage("删除成功", c)
}
